package com.auto.autoapp.task

import com.auto.autoapp.AutoApplication
import com.auto.autoapp.constants.Dy
import com.auto.autoapp.constants.HomePageId
import com.auto.autoapp.constants.VideoPageId
import com.auto.autoapp.model.SceneType
import com.auto.autoapp.step.clickLike
import com.auto.autoapp.step.exchangeVideo
import com.auto.autoapp.step.getCurrentScene
import com.auto.autoapp.step.getDyCode
import com.auto.autoapp.step.toDyIndex
import com.auto.autoapp.ui.result.ResultActivity
import com.auto.autoapp.util.SpUtil
import com.auto.autoapp.util.StringUtil
import com.auto.autoapp.util.addLog
import com.auto.autoapp.util.clickOrTap
import com.auto.autoapp.util.getNodeById
import com.ven.assists.AssistsCore
import com.ven.assists.AssistsCore.setNodeText
import com.ven.assists.stepper.Step
import com.ven.assists.stepper.StepCollector
import com.ven.assists.stepper.StepImpl
import kotlinx.coroutines.delay

/**
 * 主播新视频监听并评论
 * 对指定的主播进行监听，发现有新作品立即进行评论等相关操作
 * 1、获取当前抖音号
 * 2、进入主播主页，查看是否有新视频
 * 3、播放每一个新视频
 * 4、视频点赞
 * 5、循环3---4
 * 6、循环2---5
 *
 *
 */
class UpVideoListenTask : StepImpl() {

    override fun onImpl(collector: StepCollector) {
        // 读取本地配置
        var setting = SpUtil.getUpSettings()
        //尝试查找新视频的次数
        var retryCount = 0
        //当前主播列表下表
        var currentIndex = 0

        collector
            // Step 1: 前往首页并获取当前抖音号
            .next(1) {
                setting = SpUtil.getUpSettings()
                retryCount = 0
                currentIndex = 0
                return@next toDyIndex(nextStep = 2)
            }
            .next(2) {
                addLog("跳转首页成功，开始切换tab->我的")

                val result = Dy.ID_TAB_MINE.clickOrTap()
                if (result.isFailure) {
                    addLog("切换至我的页面失败")
                    return@next Step.repeat
                }
                delay(1500)
                val codeResult = getDyCode()
                if (codeResult.isFailure) {
                    ResultActivity.open(AutoApplication.instance, "未获取到抖音号，请确认是否已登录")
                    addLog("未获取到抖音号，请确认是否已登录")
                    return@next Step.none
                }
                delay(500)
                val indexTab = Dy.ID_TAB_MINE.getNodeById(last = false)
                if (indexTab.isFailure) {
                    addLog("无法切换至首页，请检查页面")
                    return@next Step.none
                }

                val toIndexResult = indexTab.getOrNull()!!.clickOrTap()
                if (toIndexResult.isSuccess) {
                    addLog("切换至首页成功")
                } else {
                    addLog("切换至首页失败")
                }
                return@next Step.get(3)

            }
            // Step 3: 搜索关键字
            .next(3) {
                val searchNodeResult = Dy.ID_INDEX_SEARCH_NODE.clickOrTap()
                if (searchNodeResult.isFailure) {
                    addLog("未找到搜索入口，请重试")
                    AssistsCore.back()
                    delay(1500)
                    return@next Step.repeat
                }
                delay(2000)
                val editText = AssistsCore.findById(Dy.ID_SEARCH_INPUT).firstOrNull()
                if (currentIndex >= setting.anchorList.size) {
                    addLog("主播设置错误，将重新开始")
                    currentIndex = 0
                    return@next Step.repeat
                }
                val currentUp = setting.anchorList[currentIndex]
                if (editText != null) {
                    editText.setNodeText(currentUp)
                    delay(500)
                    Dy.SEARCH_BTN.clickOrTap()
                    addLog("已执行搜索")
                    delay(3000)
                    addLog("scene:${getCurrentScene().getOrNull()}")
                    if (getCurrentScene().getOrNull() != SceneType.HOME_PAGE) {
                        addLog("无法跳转主播主页，请检查主播地址")
                        return@next Step.none
                    }
                    retryCount = 0
                    return@next Step.get(4)

                } else {
                    addLog("搜索输入框未找到")
                    return@next Step.none
                }
            }.next(4) {
                //获取作品rv
                var rvVideo = HomePageId.RV_VIDEO.getNodeById().getOrNull()
                if (rvVideo == null) {
                    addLog("未找到作品列表")
                    currentIndex++
                    if (currentIndex >= setting.anchorList.size) {
                        currentIndex = 0
                    }
                    AssistsCore.back()
                    delay(500)
                    return@next Step.get(3)
                } else {
                    val firstVideo =
                        rvVideo.findAccessibilityNodeInfosByViewId(HomePageId.CONTAINER_VIDEO)
                            .firstOrNull()
                    if (firstVideo == null) {
                        addLog("未找到作品")
                        currentIndex++
                        if (currentIndex >= setting.anchorList.size) {
                            currentIndex = 0
                        }
                        AssistsCore.back()
                        delay(500)
                        return@next Step.get(3)
                    } else {
                        val seeResult = firstVideo.clickOrTap()
                        if (seeResult.isSuccess) {
                            addLog("点击视频成功")
                            return@next Step.get(5)
                        } else {
                            addLog("点击视频失败")
                            return@next Step.repeat
                        }
                    }
                }

                return@next Step.none
            }.
                //查找发布时间
            next(5) {
                val publishInfo = VideoPageId.PUBLISH_INFO.getNodeById()
                if (publishInfo.isFailure) {
                    addLog("未找到发布信息")
                    retryCount++
                    return@next Step.get(6)
                }
                val info = publishInfo.getOrNull()!!.text

                val diffDays = StringUtil.diffDays(info.toString())
                addLog("作品已发布：${diffDays}天,搜索范围为${setting.intervalDays}天")
                //不在最新时间范围
                if (diffDays == null || diffDays > setting.intervalDays) {
                    retryCount++
                    addLog("作品发布信息为：${info},不在规定天数内")
                    return@next Step.get(6)
                }

                val likeResult = clickLike()
                delay(1200)
                if (likeResult.isSuccess) {
                    addLog("点赞成功")
                    currentIndex++
                    retryCount = 0
                    AssistsCore.back()
                    delay(1200)
                    AssistsCore.back()
                    delay(1200)
                    return@next Step.get(3)
                } else {
                    addLog("点赞失败")
                    return@next Step.get(6)
                }


            }.next(6) {
                if (retryCount > setting.retryCount) {
                    AssistsCore.back()
                    delay(1500)
                    AssistsCore.back()
                    delay(1500)
                    AssistsCore.back()
                    delay(1500)
                    currentIndex++
                    retryCount = 0
                    return@next Step.get(3)
                }

                val exchange = exchangeVideo()
                if (exchange.isFailure) {
                    addLog("滑屏进入下一个视频失败")
                    AssistsCore.back()
                    delay(1000)
                    AssistsCore.back()
                    delay(1000)
                    AssistsCore.back()
                    delay(1000)
                    currentIndex++
                    retryCount = 0
                    return@next Step.get(3)
                }

                return@next Step.get(5)

            }


    }
}